package com.xtayfjpk.zookeeper.test.master_workers.curator.listener;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.log4j.Logger;

import com.xtayfjpk.zookeeper.test.master_workers.curator.CuratorMaster;

public class MasterListener implements CuratorListener {
	private static final Logger LOGGER = Logger.getLogger(MasterListener.class);
	
	private CuratorMaster master;
	
	public MasterListener(CuratorMaster curatorMaster) {
		this.master = curatorMaster;
	}

	@Override
	public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
		LOGGER.info("Event path: " + event.getPath());
		
		switch (event.getType()) {
		case CHILDREN:
			if(event.getPath().contains("/assign")) {
				LOGGER.info("Succesfully got a list of assignments: " 
                        + event.getChildren().size() 
                        + " tasks");
				
				/*
	             * Delete the assignments of the absent worker
	             */
				for(String task : event.getChildren()) {
					master.deleteAssignment(event.getPath() + "/" + task);
				}
				
				/*
                 * Delete the znode representing the absent worker
                 * in the assignments.
                 */
				master.deleteAssignment(event.getPath());
				
				/*
                 * Reassign the tasks.
                 */
                master.assignTasks(event.getChildren());
			} else {
				LOGGER.warn("Unexpected event: " + event.getPath());
			}
			break;
			
		case CREATE:
			if(event.getPath().contains("/assign")) {
				LOGGER.info("Task assigned correctly: " + event.getName());
				master.deleteTask(event.getPath().substring(event.getPath().lastIndexOf('-') + 1));
			}
			break;
			
		case DELETE:
			if(event.getPath().contains("/tasks")) {
                LOGGER.info("Result of delete operation: " + event.getResultCode() + ", " + event.getPath());
            } else if(event.getPath().contains("/assign")) {
                LOGGER.info("Task correctly deleted: " + event.getPath());
            }
			break;

		default:
			LOGGER.error("Default case: " + event.getType());
			break;
		}
	}

}
